package com.yanchangapp.ui.activity.purchase.approve;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.luck.picture.lib.decoration.RecycleViewDivider;
import com.luck.picture.lib.tools.ScreenUtils;
import com.yanchangapp.R;
import com.yanchangapp.adapter.SupplierAdapter;
import com.yanchangapp.adapter.part.OrderTwiceAdapter;
import com.yanchangapp.adapter.part.ProductEditNumAdapter;
import com.yanchangapp.commom.AppConstant;
import com.yanchangapp.commom.CompanyType;
import com.yanchangapp.commom.LoadingType;
import com.yanchangapp.model.bean.RecordProductBean;
import com.yanchangapp.model.bean.SupplierBean;
import com.yanchangapp.model.cache.UserCache;
import com.yanchangapp.model.response.RecordDetailResponse;
import com.yanchangapp.ui.presenter.ApproveWaitDetailAtPresenter;
import com.yanchangapp.ui.view.ApproveWaitDetailAtView;
import com.yanchangapp.widget.BottomDialog;
import com.yanchangapp.widget.RejectReasonDialog;
import com.yanchangapp.widget.SpannableMoney;
import com.yanchangapp.widget.SupplierListBottomDelegate;
import com.yanchangapp.widget.SupplierNumDialog;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.formatter.BigDecimalUtils;
import com.zxl.baselib.util.ui.ResHelper;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.widget.NiceNestedScrollView;
import com.zxl.baselib.widget.YCLoadingView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.yanchangapp.ui.activity.purchase.approve.GoodsApproveActivity.REFRESH_APPROVE_DATA;

/**
 * 待审批详情界面....
 *
 * *****
 */
public class WaitApprovePassDetailActivity extends BaseActivity<ApproveWaitDetailAtView, ApproveWaitDetailAtPresenter> implements ApproveWaitDetailAtView, OrderTwiceAdapter.RecordProductListener {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.tvTotalNumMoney)
    TextView tvTotalNumMoney;
    @BindView(R.id.tvReject)
    TextView tvReject;
    @BindView(R.id.tvPassEmail)
    TextView tvPassEmail;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.tvTag)
    TextView tvTag;
    @BindView(R.id.tvBuyerNameTitle)
    TextView tvBuyerNameTitle;
    @BindView(R.id.tvBuyerName)
    TextView tvBuyerName;
    @BindView(R.id.tvTimeTitle)
    TextView tvTimeTitle;
    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.rvOrderDetail)
    RecyclerView rvOrderDetail;
    @BindView(R.id.scrollView)
    NiceNestedScrollView scrollView;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    @BindView(R.id.ycLoading)
    YCLoadingView ycLoading;
    @BindView(R.id.rlEmailDetail)
    RelativeLayout rlEmailDetail;
    // 第一个sheet 包括供货方+数量
    // 第二个sheet 供货方列表展示...
    // 选中的供货商ID以及供货商姓名...
    private String selectSupplierId, selectSupplierName;
    private int selectNum;
    private int currentIndex;
    private int mInnerRecommend;
    private String currentNum,tips;
    private int mInnerSmall;
    private int mID;
    private static final String ID = "id";
    private List<RecordProductBean> mRecordProductBeans = new ArrayList<>();
    private OrderTwiceAdapter mOrderTwiceAdapter;
    private int totalProduct;
    private SupplierNumDialog mSupplierNumDialog;
    private SupplierListBottomDelegate.Builder mSupplierBuilder;
    private RejectReasonDialog mReasonDialog;
    private boolean mIsAllThreePart = true;

    public static void show(Activity activity, int id) {
        Intent intent = new Intent(activity, WaitApprovePassDetailActivity.class);
        intent.putExtra(ID, id);
        activity.startActivity(intent);
    }

    @Override
    protected void init() {
        if (getIntent() != null && getIntent().hasExtra(ID)) {
            mID = getIntent().getIntExtra(ID, -1);
        } else {
            finish();
        }
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_wait_approve_detail;
    }

    @Override
    protected ApproveWaitDetailAtPresenter createPresenter() {
        return new ApproveWaitDetailAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvToolbarTitle.setText("审批详情");
        initAdapter();
        setLookEmail();
    }

    private void setLookEmail() {
        if (UserCache.getCompanyType() == 12){
            rlEmailDetail.setVisibility(View.VISIBLE);
        }else {
            rlEmailDetail.setVisibility(View.GONE);
        }

    }

    private void initAdapter() {
        // 设置商品的Adapter
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        rvOrderDetail.setHasFixedSize(true);
        rvOrderDetail.setNestedScrollingEnabled(false);
        rvOrderDetail.setLayoutManager(manager);
        mOrderTwiceAdapter = new OrderTwiceAdapter(this, mRecordProductBeans, this);
        mOrderTwiceAdapter.justSetType();
        rvOrderDetail.setAdapter(mOrderTwiceAdapter);
    }

    @Override
    protected void initData() {
        setLoadingState(LoadingType.LOADING);
        mPresenter.queryRecordDetail(mID);
    }

    private void setLoadingState(LoadingType loadingType) {
        switch (loadingType) {
            case LOADING:
                if (ycLoading.getVisibility() == View.GONE) {
                    ycLoading.setVisibility(View.VISIBLE);
                }

                if (scrollView.getVisibility() == View.VISIBLE) {
                    scrollView.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE) {
                    llErrorNetwork.setVisibility(View.GONE);
                }
                break;
            case SUCCESS:

                if (ycLoading.getVisibility() == View.VISIBLE) {
                    ycLoading.setVisibility(View.GONE);
                }

                if (scrollView.getVisibility() == View.GONE) {
                    scrollView.setVisibility(View.VISIBLE);
                    bottom.setVisibility(View.VISIBLE);
                }


                if (llErrorNetwork.getVisibility() == View.VISIBLE) {
                    llErrorNetwork.setVisibility(View.GONE);
                }
                break;
            case ERROR:
                if (ycLoading.getVisibility() == View.VISIBLE) {
                    ycLoading.setVisibility(View.GONE);
                }

                if (scrollView.getVisibility() == View.VISIBLE) {
                    scrollView.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }


                if (llErrorNetwork.getVisibility() == View.GONE) {
                    llErrorNetwork.setVisibility(View.VISIBLE);
                }
                break;
            default:
                break;
        }
    }


    @Override
    protected void initListener() {
        ivToolbarNavigation.setOnClickListener(v -> {
            finish();
        });

        tvReject.setOnClickListener(v -> showRejectDialog());


        // 通知并发送邮件事件...
        tvPassEmail.setOnClickListener(v -> mPresenter.passRecord(mID));

        btnNextRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initData();
            }
        });

        rlEmailDetail.setOnClickListener(v ->
                EmailDetailActivity.show(WaitApprovePassDetailActivity.this,mID));
    }

    private void showSupplierNum(){
        mSupplierNumDialog = new SupplierNumDialog.Builder(this)
                .setBuyNum(currentNum)
                .setBuyRange(mInnerSmall,mInnerRecommend)
                .setSupplierName(selectSupplierName)
                .setTipsString(tips)
                .setEnsureListener(this::recallBackData)
                .setJumpSupplierListener(numStr -> {
                    currentNum = numStr;
                    showSupplierBottom();
                })
                .build();
        mSupplierNumDialog.show();
    }

    private void recallBackData(int innerNum) {
        selectNum = innerNum;
        mPresenter.submitRecord(mRecordProductBeans.get(currentIndex).getId(), selectSupplierId, innerNum);
    }

    private void showSupplierBottom(){
        if (mSupplierBuilder == null){
            mSupplierBuilder = new SupplierListBottomDelegate.Builder(this)
                    .setDismissListener(this::showSupplierNum)
                    .setEnsureListener((supplierID, supplierName) -> {
                        selectSupplierId = supplierID;
                        selectSupplierName = supplierName;
                    })
                    .create();
        }
        mSupplierBuilder.setData(mRecordProductBeans.get(currentIndex).getSuppliers())
                .setSelectSupplier(selectSupplierId)
                .show();
    }



    private void showRejectDialog(){
        mReasonDialog = new RejectReasonDialog.Builder(this)
                .setRejectListener(new RejectReasonDialog.RejectReasonListener() {
                    @Override
                    public void onReject(String reason) {
                        mPresenter.rejectRecord(mID,reason);
                    }
                })
                .create();
        mReasonDialog.show();
    }



    @Override
    public void queryDetailSuccess(RecordDetailResponse response) {
        setLoadingState(LoadingType.SUCCESS);
        // 设置对应的标签信息...
        tvTag.setText(response.getExamineStatusName());
        tvTag.setBackground(ResHelper.getDrawable(R.drawable.tag_order_submit));
        tvBuyerName.setText(getString(R.string.order_detail_name_dept, response.getBuyer(), response.getDepartment()));
        // 设置创建时间...
        tvTime.setText(response.getCreateTime());
        // 刷新商品列表的数据
        mRecordProductBeans.addAll(response.getRecords());
        mOrderTwiceAdapter.notifyDataSetChanged();
        totalProduct = mRecordProductBeans.size();
        setTotalMoney(response.getTotalMoney());
        setBottomState();
    }

    private void setTotalMoney(double money) {
        String totalMoney = BigDecimalUtils.keep2Decimal(money);
        int len = totalMoney.length();
        SpannableString spannableString = new SpannableString(
                ResHelper.getString(R.string.down_order_sum, String.valueOf(totalProduct), totalMoney));
        int totalLength = spannableString.length();
        spannableString.setSpan(new SpannableMoney(WaitApprovePassDetailActivity.this),
                totalLength - len - 1, totalLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvTotalNumMoney.setText(spannableString);
    }

    private void setBottomState() {
        checkIsAllThreePart();
        if (mIsAllThreePart){
            tvPassEmail.setText("通过");
        }
    }

    /**
     * 检查订单数据是否都是第三方数据
     */
    private void checkIsAllThreePart(){
        if (mRecordProductBeans.size() == 0){
            mIsAllThreePart = true;
            return;
        }
        for (int i=0;i<mRecordProductBeans.size();i++){
            int thirdFlag = mRecordProductBeans.get(i).getIsThirdFlag();
            if (thirdFlag == CompanyType.NOT_THIRD_PART.value){
                mIsAllThreePart = false;
                return;
            }
        }
    }


    @Override
    public void queryDetailFailure(String err) {
        setLoadingState(LoadingType.ERROR);
        UIUtils.showToast(err);
    }

    @Override
    public void editRecordSuccess(double totalMoney) {
        RecordProductBean bean = mRecordProductBeans.get(currentIndex);
        bean.setPurchaseNum(selectNum);
        bean.setSupplierId(selectSupplierId);
        bean.setSupplierName(selectSupplierName);
        mOrderTwiceAdapter.notifyItemChanged(currentIndex, ProductEditNumAdapter.JUST_REFRESH_NUM_SUPPLIER);
        // 进行隐藏
        mSupplierNumDialog.dismiss();
        UIUtils.showToast("修改成功");
        setTotalMoney(totalMoney);
    }

    @Override
    public void editRecordFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void rejectRecordFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void rejectRecordSuccess() {
        UIUtils.showToast("驳回成功");
        mReasonDialog.dismiss();
        mRxManager.post(REFRESH_APPROVE_DATA,true);
        finish();
    }

    @Override
    public void passRecordFailure(String err) {
        UIUtils.showToast(err);
    }

    @Override
    public void passRecordSuccess() {
        UIUtils.showToast("通过并已发送邮件");
        // 关闭弹层
        mRxManager.post(REFRESH_APPROVE_DATA,true);
        finish();
    }

    // 编辑数量的点击事件...
    @Override
    public void onProductNumClick(int position) {
        currentIndex = position;
        // 设置数据并进行显示
        RecordProductBean bean = mRecordProductBeans.get(currentIndex);
        selectSupplierId = String.valueOf(bean.getSupplierId());
        selectSupplierName = bean.getSupplierName();
        mInnerRecommend = bean.getAlarmMax() - bean.getInventoryNumber();
        mInnerSmall = bean.getAlarmMin() - bean.getInventoryNumber();
        if (mInnerSmall < 0){
            mInnerSmall = 0;
        }
        if (mInnerRecommend == 0) {
            tips = "库存无法存放";
        } else {
           tips = getString(R.string.apply_tips, mInnerSmall, mInnerRecommend);
        }
        currentNum = String.valueOf(bean.getPurchaseNum());
        showSupplierNum();
    }

    @Override
    public void onLookDetail() {
        EmailDetailActivity.show(WaitApprovePassDetailActivity.this,mID);
    }

}
